% Written by Samuel Hurtado



function G2_new = unfoldg2(G2,n)

% This function is designed to "unfold" matrix g_2 generated in the third
% order approximation of a policy function in Dynare.
% Arguments:
% G2 => matrix g_2, normally stored at oo_.dr.g_2, after the computation of
% a third-order approximation;
% n => number of state variables + shocks in the model (easy: n=size(G1,2))



% replicate the order in which Dynare stored these numbers, leave zero on the elements that were discarded

G2_index=zeros(n,n);

mycounter=0;
totalcounter = size(G2,2);
for x=1:n
for y=x:n
    mycounter=mycounter+1;
                tracker = mycounter/totalcounter*100;
            %disp(['tracker ' num2str(tracker) '%']);
    G2_index(x,y)=mycounter;
end
end



% populate G2_new, pulling out of G2 the elements designated by G2_index
% (when choosing elements of G2_index, sort index to avoid all the elements that were discarded)

G2_new = zeros(size(G2,1),n^2);

mycounter=0;
totalcounter = n*n;
for x=1:n
for y=1:n
    mycounter = mycounter+1;
                tracker = mycounter/totalcounter*100;
            %disp(['tracker ' num2str(tracker) '%']);
    xy=sort([x y]);
    G2_new(:,mycounter)=G2(:,G2_index(xy(1),xy(2)));
end
end


